package com.example.user3.demo.utils;

import android.content.Context;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.widget.Toast;


public class MaxTextLengthFilter implements InputFilter {

    private int mMaxLength;
    private Context ctx;
    String content;
    //构造方法中传入最多能输入的字数
    public MaxTextLengthFilter(Context context, int max) {
        mMaxLength = max;
        ctx=context;
    }
    public MaxTextLengthFilter(Context context, int max, String content) {
        mMaxLength = max;
        ctx=context;
        this.content=content;
    }
    public CharSequence filter(CharSequence source, int start, int end,
                               Spanned dest, int dstart, int dend) {
        int keep = mMaxLength - (dest.length() - (dend - dstart));
        if (keep < (end - start)) {
            if(TextUtils.isEmpty(content)){
                Toast.makeText(ctx,"最多只能输入"+mMaxLength+"个字",Toast.LENGTH_SHORT);
            }else{
                Toast.makeText(ctx,content,Toast.LENGTH_SHORT);
            }

        }
        if (keep <= 0) {
            return "";
        } else if (keep >= end - start) {
            return null;
        } else {
            return source.subSequence(start, start + keep);
        }
    }
}